﻿using System;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Helpers;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Profiles
{
    public static class Utility
    {
        public static void RemoveAll(this SPAttachmentCollection coll)
        {
            var items = new string[coll.Count];

            for (var i = 0; i < coll.Count; i++)
                items[i] = coll[i];

            foreach (string attachment in items)
                coll.Delete(attachment);
        }               
        
        public static void AddBlog(this SPUser user, string title, string url, string rssUrl, string description, DateTime firstEntryDate)
        {
            var siteId = SPContext.Current.Site.ID;
            var userId = user.ID;
            var userName = user.LoginName;

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.OpenWeb("/uudised/blogid/"))
                    {
                        var list = web.Lists["Lehed"];

                        try
                        {
                            var publishingWeb = PublishingWeb.GetPublishingWeb(web);
                            var ct = web.AvailableContentTypes["Blog"];

                            var layouts = publishingWeb.GetAvailablePageLayouts(ct.Id);
                            var blogEntryLayout = layouts[0];
                            var pages = publishingWeb.GetPublishingPages();

                            var pageName = UrlHelper.GetPageFileName(title); //GetUniqueNameForTitle


                            var pageUrl = list.RootFolder.ServerRelativeUrl + "/" + pageName;
                            var counter = 1;

                        checkpage:
                            var page = web.GetFile(pageUrl);
                            if (page != null)
                                if (page.Exists)
                                {
                                    if (counter == 1)
                                        pageUrl = pageUrl.Replace(".aspx", "-1.aspx");
                                    else
                                        pageUrl = pageUrl.Replace("-" + (counter - 1) + ".aspx", "-" + counter + ".aspx");
                                    counter++;
                                    goto checkpage;
                                }

                            var publishingPage = pages.Add(pageUrl, blogEntryLayout);
                            var item = publishingPage.ListItem;

                            item["ContentTypeId"] = web.Site.RootWeb.ContentTypes["Blog"].Id;
                            item["Title"] = title;

                            var link = new SPFieldUrlValue();
                            link.Url = url;
                            link.Description = title;
                            item["URL"] = link;

                            var owner = new SPFieldUserValue(web, userId, userName);
                            item["Owner"] = owner;
                            item["PublishingPageContent"] = description;
                            item["FirstEntryDate"] = firstEntryDate;
                            item["RssUrl"] = rssUrl;

                            item.Update();

                            item.File.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
                            publishingPage.CheckIn(string.Empty);
                            item.File.Publish(string.Empty);
                            item.Update();

                        }
                        catch(Exception ex)
                        {
                            Logger.LogWarning("AddBlog(): Error when adding new blog", "Utility");
                            Logger.LogException(ex);
                            return;
                        }

                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
        }       
    }
}
